package common;

public class DoubleList {
    private DoubleListNode head;
    private DoubleListNode tail;

    public DoubleList() {
        head = null;
        tail = null;
    }

    // 添加元素
    public void addNode(DoubleListNode newNode) {
        if (newNode == null) {
            return;
        }
        if (head == null) {
            head = tail = newNode;
        } else {
            tail.next = newNode;
            newNode.last = tail;
            tail = newNode;
        }
    }

    // 删除尾元素
    public DoubleListNode remveHead() {
        if (head == null) {
            return null;
        }
        DoubleListNode ans = head;
        if (tail == head) {
            head = tail = null;
        } else {
            head = ans.next;
            ans.next = null;
            head.last = null;
        }
        return ans;
    }

    /**
     * 将node节点移动存尾
     */
    public void moveNodeToTail(DoubleListNode node) {
        if (tail == null) { // 如果节点在尾部，则不用动
            return;
        }
        if (head == node) { // 如果节点在头部，则头部节点前进到下一个节点
            head = head.next;
            head.last = null;
        } else {
            // 删除目标节点
            DoubleListNode cur = this.head;
            while (cur.next != node) {
                cur = cur.next;
            }
            DoubleListNode d = cur.next;
            cur.next = d.next;
            if (d.next != null) {
                d.next.last = cur;
            }
        }
        // 添加到尾部
        node.last = tail;
        node.next = null;
        tail.next = node;
        tail = node;
    }

    public String toString() {
        DoubleListNode t = this.head;
        StringBuilder s = new StringBuilder();
        while (t != null) {
            s.append(t.val);
            t = t.next;
            s.append(t != null ? "\t⇄\t" : "");
        }
        return s.toString();
    }
}
